odoo.define('web_ps_report.PsReportRenderer', function (require) {
    'use strict';

    var AbstractRenderer = require('web.AbstractRenderer');
    var Widget = require('web.Widget');
    var core = require('web.core');
    var field_utils = require('web.field_utils');
    var datepicker = require('web.datepicker');
    var relational_fields = require('web.relational_fields');
    var basic_fields = require('web.basic_fields');
    var StandaloneFieldManagerMixin = require('web.StandaloneFieldManagerMixin');

    var qweb = core.qweb;
    var _t = core._t;

    var PsReportRenderer = AbstractRenderer.extend(StandaloneFieldManagerMixin, {
        events: _.extend({}, AbstractRenderer.prototype.events, {
            'click .o_psreport_row_clickable': '_onClickRow',
            'click .o_search_psreport': '_onClick_Search',
            'click .o_print_psreport': '_onClick_Print',
            'click .o_download_psreport': '_onClick_Download',
            'change input.filter': '_onFilterChange',
            'click .o_collection_psreport': '_onClick_Collection',
            'click .o_show_detail_psreport': '_onClick_Show_Detail',
            'click table:eq(1)>tbody:eq(1)>tr>td': '_onClickTd',
        }),
        _avoidFieldUpdate: {},

        _onClick_Search: function () {

            this.trigger_up('search_clicked', {});
        }
        ,
        _onClick_Collection: function () {

            this.trigger_up('collection_clicked', {});
        }
        ,
        _onClick_Download: function () {
            this.trigger_up('download_clicked', {});
        },

        _onClick_Print: function () {
            this.trigger_up('print_clicked', {});
        },
        _onClick_Show_Detail: function () {
            this.trigger_up('show_detail_clicked', {});
        },
        _onClickTd: function(event){
            event.preventDefault();
            var self = this;
            var event = $(event.target);
            var amountIndex = 0;
            var show_dimension = false;
            var partner_name = false;
            var tr_length = $('table:eq(1)>tbody:eq(1)>tr:eq(0)>td').length;
            if (tr_length === 10) {
                amountIndex = 2;
            } else if (tr_length === 11) {
                amountIndex = 3;
                show_dimension = true;
                partner_name = event.parent().find('td:eq(2)').text().trim();
            };

            var y = event.data().y;
            if (y >= amountIndex && event.text().trim() !== "") {
                var acc_code = event.parent().find('td:eq(0)').text().trim();
                this._rpc({
                    model: 'nd.account.balance',
                    method: 'get_amount_action',
                    args: [acc_code, y, this.model.set_search_domian(), partner_name]
                }).then(function(result){
                    self.trigger_up('table_td_clicked', {result: result});
//                    self.model.do_action(result)
                })
            }
        },
        /**
         * @override
         * @param {Widget} parent
         * @param {Object} state
         * @param {Object} params
         * @param {Object} params.measures
         * @param {Object} params.intervals
         * @param {string} params.mode
         * @param {string} params.timeline
         */
        init: function (parent, state, params) {
            this._super.apply(this, arguments);
            StandaloneFieldManagerMixin.init.call(this);
            this.measures = params.measures;
            this.intervals = params.intervals;
            this.timeRangeDescription = params.timeRangeDescription;
            this.comparisonTimeRangeDescription = params.comparisonTimeRangeDescription;
            this.mode = params.mode;
            this.timeline = params.timeline;
            this.ps_fields = params.ps_fields;
            this.render_type = params.render_type;
            this.modelName = params.modelName;
            this.model = params.model;
            this.fields = params.fields;
            this._initialState = state;
            this.show_detail_control = false;
        },
        start: function () {
            this._super.apply(this, arguments);
            this._onClick_Search();

        },
        /**
         * @override
         * @param {Object} state
         * @param {Object} params
         */
        updateState: function (state, params) {
            if (params.context !== undefined) {
                var timeRangeMenuData = params.context.timeRangeMenuData;
                if (timeRangeMenuData) {
                    this.timeRangeDescription = timeRangeMenuData.timeRangeDescription;
                    this.comparisonTimeRangeDescription = timeRangeMenuData.comparisonTimeRangeDescription;
                } else {
                    this.timeRangeDescription = undefined;
                    this.comparisonTimeRangeDescription = undefined;
                }
            }
            return this._super.apply(this, arguments);
        }
        ,

        //--------------------------------------------------------------------------
        // Private
        //--------------------------------------------------------------------------

        _makeMany2Many: function (res) {
            var self = this;
            var options = {};
            options[res.field.attrs.name] = {
                options: {
                    no_create_edit: true,
                    no_create: true,
                    quick_create: false,
                }
            };
            if (self.model.psdata.report.defaults[res.field.attrs.name]) {
                var value = self.model.psdata.report.defaults[res.field.attrs.name];
            } else {
                var value = self.fields[res.field.attrs.name].value;
                value = value && value.res_ids;
            }
            if(self.model.psdata.report.domain){
                if (self.model.psdata.report.domain[res.field.attrs.name]) {
                    var domain = self.model.psdata.report.domain[res.field.attrs.name];
                } else {
                    var domain = [];
                }
            }


            return this.model.makeRecord(self.modelName, [{
                name: res.field.attrs.name,
                relation: res.relation,
                type: res.ttype,
                domain: domain,
            }], options).then(function (recordID) {
                self.fields[res.field.attrs.name] = new relational_fields.FieldMany2ManyTags(self,
                    res.field.attrs.name,
                    self.model.get(recordID),
                    {mode: 'edit',}
                );
                self._registerWidget(recordID, res.field.attrs.name, self.fields[res.field.attrs.name]);
                self.fields[res.field.attrs.name].replace(self.$el.find('.' + res.field.attrs.name));
                self.fields[res.field.attrs.name].$el.css("width", "80%");
                self.fields[res.field.attrs.name].$el.find('input').css("text-align", "left");
                self.fields[res.field.attrs.name].$el.find('input').addClass(res.field.attrs.name);
                //根据ID获取display_name
                _.each(value, function (id) {
                    self.fields[res.field.attrs.name]._rpc({
                        model: self.fields[res.field.attrs.name].field.relation,
                        method: "search_read",
                        args: [
                            [['id', '=', id]],
                            ['id', 'name']
                        ],
                    }).then(function (result) {
                        console.log(result)
                        if (!result || result.length == 0) return;
                        self.fields[res.field.attrs.name]._addTag({'id': id, 'display_name': _t(result[0]['name'])});

                    });
                });
            });
        },

        _makeMany2One: function (res) {
            var self = this;
            var options = {};
            options[res.field.attrs.name] = {
                options: {
                    no_create_edit: true,
                    no_create: true,
                    quick_create: false,
                }
            };
            if (self.model.psdata.report.defaults[res.field.attrs.name]) {
                var value = self.model.psdata.report.defaults[res.field.attrs.name];
            } else {
                var value = self.fields[res.field.attrs.name].value;
                value = value && value.res_id;
            }
            if(self.model.psdata.report.domain){
                if (self.model.psdata.report.domain[res.field.attrs.name]) {
                    var domain = self.model.psdata.report.domain[res.field.attrs.name];
                } else {
                    var domain = [];
                }
            }
            return self.model.makeRecord(self.modelName, [{
                relation: res.relation,
                type: res.ttype,
                name: res.field.attrs.name,
                value: value,
                domain: domain,
            }], options).then(function (recordID) {
                self.fields[res.field.attrs.name] = new relational_fields.FieldMany2One(self,
                    res.field.attrs.name,
                    self.model.get(recordID),
                    {mode: 'edit'}
                );
                self.fields[res.field.attrs.name].string = res.field.attrs.string;
                self._registerWidget(recordID, res.field.attrs.name, self.fields[res.field.attrs.name]);
                self.fields[res.field.attrs.name].replace(self.$el.find('.' + res.field.attrs.name));
                self.fields[res.field.attrs.name].$el.find('button').remove();
                self.fields[res.field.attrs.name].$el.find('input').css("text-align", "left");
            });
        },

        _makeBoolean: function (res) {
            var self = this;
            if (self.model.psdata.report.defaults[res.field.attrs.name]) {
                var value = self.model.psdata.report.defaults[res.field.attrs.name];
            } else {
                var value = self.fields[res.field.attrs.name].value;
            }
            return self.model.makeRecord(self.modelName, [{
                type: res.ttype,
                name: res.field.attrs.name,
                value: value,
            }]).then(function (recordID) {
                self.fields[res.field.attrs.name] = new basic_fields.FieldBoolean(self,
                    res.field.attrs.name,
                    self.model.get(recordID),
                    {mode: 'edit'}
                );
                self._registerWidget(recordID, res.field.attrs.name, self.fields[res.field.attrs.name]);
                self.fields[res.field.attrs.name].replace(self.$el.find('.' + res.field.attrs.name));
                self.fields[res.field.attrs.name].$el.find('input').addClass(res.field.attrs.name);
            });
        },

        _render: function () {
            var self = this;
            this.render_type = this.arch.attrs.render_type
            self._rpc({
                model: 'nd.account.balance',
                method: 'nd_report_fields_get',
                args: [self.ps_fields, self.modelName],
            }).then(function (res) {
                var arr = [];
                for (var i = 0; i < res.length; i++) {
                    //如果字段类型为date则添加上class名ps_report_date
                    if (res[i].ttype == "date") {
                        res[i].field.attrs.class = res[i].field.attrs.name;
                    } else if (res[i].ttype == "many2one") {
                        res[i].field.attrs.class = res[i].field.attrs.name;
                    } else if (res[i].ttype == "many2many") {
                        res[i].field.attrs.class = res[i].field.attrs.name;
                    } else if (res[i].ttype == "boolean") {
                        res[i].field.attrs.class = res[i].field.attrs.name;
                    } else if (res[i].ttype == "selection") {
                        res[i].field.attrs.class = res[i].field.attrs.name;
                    } else {
                        res[i].field.attrs.class = res[i].field.attrs.name;
                    }
                    arr.push(res[i].field)
                }
                if (self.render_type.indexOf('table') != -1) {
                    self.$el.empty().append(qweb.render('PsReportViewTable', {
                        report: self.model.psdata.report,
                        render_type: self.arch.attrs.render_type,
                        ps_fields: arr,
                        is_show_detail_control: self.show_detail_control,
                    }));

                }
                if (self.render_type.indexOf('qweb') != -1) {
                    var template_id = self.arch.attrs.template_id;
                    if (!template_id.length) {
                        throw new Error(_lt('您所定义的试图为Qweb类型，必须指定Template_id'));
                    }
                    self.$el.empty().append(qweb.render(template_id, {
                        report: self.model.psdata.report,
                        render_type: self.arch.attrs.render_type,
                        ps_fields: arr
                    }));
                }
                if (self.render_type.indexOf('sheetjs') != -1) {
                    self.$el.empty().append(qweb.render('PsReportViewSheetJs', {
                        report: self.model.psdata.report,
                        render_type: self.arch.attrs.render_type,
                        ps_fields: arr
                    }));
                }
                for (var i = 0; i < res.length; i++) {
                    if (res[i].ttype == "many2one") {
                        self._makeMany2One(res[i]);
                    } else if (res[i].ttype == "many2many") {
                        self._makeMany2Many(res[i]);
                    } else if (res[i].ttype == "boolean") {
                        self._makeBoolean(res[i]);
                    } else if (res[i].ttype == "selection") {
                        var options = self.fields[res[i].field.attrs.name].selection
                        var data = {
                            'options': options,
                        }
                        var $selection = $(qweb.render('PsWebReport.FieldSelection', {data}));
                        self.$el.find('.' + res[i].field.attrs.name).replaceWith($selection);
                        $selection.addClass(res[i].field.attrs.name);

                        $("." + res[i].field.attrs.name + " option[value=" + self.model.psdata.report.defaults[res[i].field.attrs.name] + "] ").attr("selected", true)
                    } else if (res[i].ttype == "date") {
                        var $datetimepickers = self.$el.find('.' + res[i].field.attrs.name);
                        var options = { // Set the options for the datetimepickers
                            locale: moment.locale(),
                            format: 'L',
                            icons: {
                                date: "fa fa-calendar",
                            },
                        };
                        $datetimepickers.datetimepicker(options);
                        console.log($datetimepickers)
                        var dt = new datepicker.DateWidget(options);
                        dt.replace($datetimepickers);
                        dt.$el.css("display", "inline-block");
                        dt.$el.find('input').attr("name", res[i].field.attrs.name);
                        dt.setValue(moment());
                    } else if (res[i].ttype == "char") {
                        self.$el.find('.' + res[i].field.attrs.name).val(self.model.psdata.report.defaults[res[i].field.attrs.name])
                    }
                }
            })

            return this._super.apply(this, arguments);
        }
        ,
        /**
         * @private
         * @param {float} value
         * @returns {string} formatted value with 1 digit
         */
        _format_float: function (value) {
            return field_utils.format.float(value, null, {
                digits: [42, 1],
            })
        }
        ,
        /**
         * @private
         * @param {float} value
         * @returns {string} formatted value with 1 digit
         */
        _format_percentage: function (value) {
            return field_utils.format.percentage(value, null, {
                digits: [42, 1],
            })
        }
        ,

        //--------------------------------------------------------------------------
        // Handlers
        //--------------------------------------------------------------------------

        /**
         * @private
         * @param {MouseEvent} event
         */
        _onClickRow: function (event) {
            var rowData = $(event.currentTarget).data();
            var rowIndex = rowData.row;
            var tableIndex = rowData.z;
            var fullDomain = this.model.psdata.report.rows[tableIndex]['act_domains'][rowIndex];
            var act_title = this.model.psdata.report.rows[tableIndex]['act_title'];
            if (this.model.psdata.report.rows[tableIndex]['act_view']){
                 var act_view = this.model.psdata.report.rows[tableIndex]['act_view'][rowIndex];
            }
            var start_act_model = this.model.psdata.report.rows[tableIndex]['act_model'];
            var act_model;
            if (start_act_model instanceof Array) {
                act_model = start_act_model[rowIndex];
            }

            else {
                act_model = start_act_model;
            }
            if (fullDomain) {
                this.trigger_up('row_clicked', {domain: fullDomain, act_model: act_model, act_title: act_title, act_view: act_view,});
            } else {
                return;
            }
        }
        ,
    });

    return PsReportRenderer;

});